package com.andy.qi.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.andy.qi.conf.RoomServerConf;
import com.andy.qi.domain.ServerInfo;
import com.andy.qi.service.RoomService;
import com.andy.qi.util.Http;
import com.andy.qi.util.StrUtils;

@RestController
public class InnerController extends WebApi {
    
    @Autowired private RoomService roomService;
    
    @Autowired private RoomServerConf config;
    
    @RequestMapping("/register_gs")
    Object register_gs(HttpServletRequest req, String id, String clientip,int clientport,int httpPort, int load) {
        
        String ip = req.getRemoteAddr();
        String tid = clientip + ":" + clientport;

        if(roomService.containsServer(tid)){
            ServerInfo info = roomService.getServer(tid);
            if(info.clientport != clientport
                || info.httpPort != httpPort
                || !info.ip.equals(ip)
            ){
                return new WebResult(1, "duplicate gsid:" + tid);
            }
            info.load = load;
            Map<String, Object> result = result();
            result.put("ip", ip);
            return new WebResult(0, "ok", result);
        }
        
        ServerInfo info = new ServerInfo();
        info.ip=ip;
        info.id=tid;
        info.clientip=clientip;
        info.clientport=clientport;
        info.httpPort=httpPort;
        info.load=load;
        roomService.setServer(tid, info);
        
        // TODO
        printServerInfo(id, ip, httpPort, clientport);
        
        Map<String, Object> result = result();
        result.put("ip", ip);
        return new WebResult(0, "ok", result);
    }
    
    private void printServerInfo(String id, String ip, int httpPort, int clientport) {
        System.out.println("game server registered.\n\tid:" + id + "\n\taddr:" + ip + "\n\thttp port:" + httpPort + "\n\tsocket clientport:" + clientport);
        
        Map<String, String> reqdata = new HashMap<>();
        reqdata.put("serverId", id);
        reqdata.put("sign", StrUtils.md5(id + config.getRoomPriKey()));
        //获取服务器信息
        String retStr = Http.get("http://" + ip + ":" + httpPort + "/get_server_info", reqdata);
        System.out.println("get_server_info:" + retStr);
    }
}